package de.kalinasch.pa.placereminder;

import java.util.List;

import android.graphics.drawable.Drawable;
import android.os.Bundle;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

import de.kalinasch.pa.placereminder.util.MapItem;

/**
 * This class displays the map and adds a icon on the saved position. 
 * 
 * @author dkalinasch
 */
public class ShowOnMapActivity extends MapActivity {
	public final static String ZOOM_LOCATION = "center";

	private MapController mapController;
	private MapView mapView;

	private double latitude;
	private double longitude;
	private int radius;
	private String title;
	private String desc;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.showonmap);

		GeoPoint position = readPositionData();
 
		zoomMapToPosition(position);

		addPositionItem(position);
	}

	@Override
	protected boolean isRouteDisplayed() {

		return false;
	}

	/**
	 * Reads the position data from the given intent and creates a GeoPosition object.
	 * 
	 * @return GeoPoint with the saved position
	 */
	private GeoPoint readPositionData() {
		latitude = getIntent().getExtras().getDouble(ActiveReminderActivity.MAP_LATITUDE);
		longitude = getIntent().getExtras().getDouble(ActiveReminderActivity.MAP_LONGITUDE);
		radius = getIntent().getExtras().getInt(ActiveReminderActivity.MAP_RADIUS);
		title = getIntent().getExtras().getString(ActiveReminderActivity.MAP_TITLE);
		desc = getIntent().getExtras().getString(ActiveReminderActivity.MAP_DESC); 

		int latPoint = (int) (latitude * 1e6);
		int longPoint = (int) (longitude * 1e6);
		return new GeoPoint(latPoint, longPoint);
	}

	/**
	 * The method handles the display of the correct part of the map.
	 * 
	 * @param _position
	 *            contains the data of the position that should be displayed
	 */
	private void zoomMapToPosition(GeoPoint _position) {
		mapView = (MapView) findViewById(R.id.mapview);
		mapView.setBuiltInZoomControls(true);
		mapController = mapView.getController();
		if (radius == 100) {
			mapController.setZoom(18);
		} else {
			mapController.setZoom(15);
		}
		mapController.animateTo(_position);
	}

	/**
	 * The method displays the position of the saved place on the map.
	 * 
	 * @param _position
	 *            contains the data of the position that should be displayed
	 */
	private void addPositionItem(GeoPoint _position) {
		List<Overlay> mapOverlays = mapView.getOverlays();
		Drawable drawable = this.getResources().getDrawable(R.drawable.blue_pin);
		MapItem itemizedoverlay = new MapItem(drawable, this);

		OverlayItem overlayitem = new OverlayItem(_position, title, desc);

		itemizedoverlay.addOverlay(overlayitem);
		mapOverlays.add(itemizedoverlay);
	}

}
